package com.sunxd.zstudy.juc;

import com.google.common.collect.Lists;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 控制线程 停止、继续
 *
 * @author: 作者名称
 * @date: 2021-09-02 15:34
 **/
public class T15_1Condition {

    public static ReentrantLock lock = new ReentrantLock();
    public static Condition producer = lock.newCondition();
    public static Condition consumer = lock.newCondition();
    static List<String> list = Lists.newArrayList();
    static int count = 1;

    public static void main(String[] args) throws IOException {
        for (int i = 0 ;i<2;i++){
            new Thread(() -> put(),"thread" + i).start();
        }


        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true){
                    System.out.println(getFirst());
                }
            }).start();
        }

        System.in.read();

    }

    public static void put(){
        lock.lock();
        try {
            while (true){
                while (list.size() == 10) {
                    System.out.println("producer await size:" + list.size());
                    producer.await();
                }
                list.add(Thread.currentThread().getName()+ "a:" + count);
                ++count;
                consumer.signalAll();
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
    }

    public static String getFirst(){
        String s = "";
        lock.lock();//请求锁
        try {
            Thread.sleep(2000);//休息2秒
            while (list.size() == 0) {
                consumer.await();
            }
            s = list.remove(0);
            producer.signalAll();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return s;
    }
}
